package cn.bannerplayerlibrary.view.newbanner;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.target.ViewTarget;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;

import java.util.concurrent.TimeUnit;

import cn.bannerplayerlibrary.R;
import cn.bannerplayerlibrary.WeakHandler;
import cn.bannerplayerlibrary.data.BannerData;
import cn.bannerplayerlibrary.view.PlayAttrs;

public class NewPlayerBannerView extends FrameLayout implements NewBannerPlayerView {

    private static final String TAG = "NewBannerPlayerView";
    private static final boolean SHOW_LOG = true;

    private MultiVideo mPlayerView;
    private ImageView mImageView;
    private BannerData mData;

    private PlayListener mListener;
    private int mIndex;

    private WeakHandler mHandler = new WeakHandler();
    private PlayAttrs mPlayAttrs;

    private boolean mPlaying;

    private ViewTarget<ImageView, Drawable> mImageTarget;
    private RequestOptions mRequestOptions;
    private int mTargetWidth;
    private int mTargetHeight;
    private String tag = "standardGSYVideoPlayer";

    public NewPlayerBannerView(Context context) {
        super(context);
        intView(context);
    }

    public NewPlayerBannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        intView(context);
    }

    public NewPlayerBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        intView(context);
    }


    private void intView(Context context) {

        // 播放控件
        mPlayerView = new MultiVideo(context);
        mPlayerView.setPlayTag(tag);
//增加title
        mPlayerView.getTitleTextView().setVisibility(View.GONE);

        //设置返回键
        mPlayerView.getBackButton().setVisibility(View.GONE);
        mPlayerView.getStartButton().setVisibility(View.GONE);
        mPlayerView.getFullscreenButton().setVisibility(View.GONE);
        mPlayerView.setRotateViewAuto(true);
        mPlayerView.setLockLand(true);
        mPlayerView.setReleaseWhenLossAudio(false);
        mPlayerView.setShowFullAnimation(true);
        mPlayerView.setIsTouchWiget(false);
        mPlayerView.setNeedLockFull(true);
        mPlayerView.setProgressBar(false);
        mPlayerView.setBottomProgressBar(false);
        mPlayerView.setVideoAllCallBack(new GSYSampleCallBack() {


//            @Override
//            public void onQuitFullscreen(String url, Object... objects) {
//                super.onQuitFullscreen(url, objects);
////                fullKey = "null";
//            }

//            @Override
//            public void onEnterFullscreen(String url, Object... objects) {
//                super.onEnterFullscreen(url, objects);
////                standardGSYVideoPlayer.getCurrentPlayer().getTitleTextView().setText((String) objects[0]);
//            }

            @Override
            public void onComplete(String url, Object... objects) {
                super.onComplete(url, objects);
                // 如果是强制播放时间，，而且还没结束，就设置重新播放
                if (mPlayAttrs != null && (mPlayAttrs.forcePlayDuration || mPlayAttrs.count == 1)) {
                    if (mPlaying) {
                        mPlayerView.seekTo(0);
                        play();
                    }
                    return;
                }
                // 执行停止
                onStop();
            }

            @Override
            public void onPlayError(String url, Object... objects) {
                super.onPlayError(url, objects);
                log(Log.ERROR, "index=" + getIndex() + ",执行onPlayerError");
                mPlaying = false;
//                Log.d("tag_mPlayNextTask", "onPlayError");
                removeCallbacks();
                onStop();
                // 播放异常
                if (mListener != null) {
                    mListener.onPlayError((NewBannerPlayerView) getSelf());
                } // 执行停止


            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);
                // 如果是强制播放时间，，而且还没结束，就设置重新播放
                if (mPlayAttrs != null && (mPlayAttrs.forcePlayDuration || mPlayAttrs.count == 1)) {
                    if (mPlaying) {
                        mPlayerView.seekTo(0);
                        play();
                    }
                    return;
                }
                // 执行停止
                onStop();
            }
        });
//        mPlayerView.
//        mPlayerView.setVideoAllCallBack(new Vide);
//        mPlayerView.setVideoAllCallBack(new PlayerView.Listener() {
//            @Override
//            public void onPrepared(PlayerView playerView) {
//
//            }
//
//            @Override
//            public void onCompleted(PlayerView playerView) {
//                // 如果是强制播放时间，，而且还没结束，就设置重新播放
//                if (mPlayAttrs != null && (mPlayAttrs.forcePlayDuration || mPlayAttrs.count == 1)) {
//                    if (mPlaying) {
//                        mPlayerView.seekTo(0);
//                        play();
//                    }
//                    return;
//                }
//                // 执行停止
//                onStop();
//            }
//
//            @Override
//            public void onError(PlayerView playerView) {
//                log(Log.ERROR, "index=" + getIndex() + ",执行onPlayerError");
//                mPlaying = false;
//                removeCallbacks();
//                // 播放异常
//                if (mListener != null) {
//                    mListener.onPlayError((NewBannerPlayerView) getSelf());
//                }
//            }
//        });

        addView(mPlayerView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        mImageView = new ImageView(context);
        addView(mImageView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        mRequestOptions = RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL)
                //.skipMemoryCache(false)
                .placeholder(R.drawable.shape_white).dontAnimate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int width = w;
        int height = h;
        if (mPlayAttrs != null) {
            mTargetWidth = (int) (w * mPlayAttrs.overrideImageScale);
            mTargetHeight = (int) (h * mPlayAttrs.overrideImageScale);
        }
    }

    @Override
    public void setListener(PlayListener listener) {
        mListener = listener;
    }

    @Override
    public ImageView getImageView() {
        return mImageView;
    }

    @Override
    public void setData(BannerData data) {
        mData = data;
        updateChildViewVisible(data);
    }

    private void updateChildViewVisible(BannerData data) {
        switch (data.getType()) {
            case BannerData.TYPE_IMAGE:
                mImageView.setVisibility(VISIBLE);
                mPlayerView.setVisibility(GONE);
                break;
            case BannerData.TYPE_VIDEO:
                mImageView.setVisibility(GONE);
                mPlayerView.setVisibility(VISIBLE);
                break;
            default:
                mImageView.setVisibility(GONE);
                mPlayerView.setVisibility(GONE);
                break;
        }
    }

    @Override
    public void setIndex(int index) {
        mIndex = index;
        mPlayerView.setPlayPosition(mIndex);
    }

    @Override
    public int getIndex() {
        return mIndex;
    }

    @Override
    public BannerData getData() {
        return mData;
    }

    @Override
    public void prepare() {

        log(Log.ERROR, "index=" + getIndex() + ",执行prepare");

        if (mData == null) {
            return;
        }

        switch (mData.getType()) {
            case BannerData.TYPE_IMAGE:
                // 如果是图片类型，则直接加载图片
                loadImage();
                break;
            case BannerData.TYPE_VIDEO:
                // 视频的话，就准备载入，当不播放
                if (!isPlaying()) {
                    mPlayerView.setPlayTag(tag);
                    mPlayerView.setUpLazy(mData.getUrl(), true, null, null, "这是title");
                }
//                mPlayerView.p();
                break;
            default:
                // 其他类型就不管了
                break;
        }
    }

    private boolean isFailed = false;

    /**
     * 加载图片
     */
    private void loadImage() {

        try {
            Glide.with(this).clear(mImageView);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        isFailed = false;
        mImageTarget = Glide.with(this)
                .load(mData.getUrl())
                .apply(mRequestOptions.override(mTargetWidth, mTargetHeight)).addListener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        isFailed = true;
                        if (mListener != null && mPlayAttrs != null && mPlayAttrs.currentIndex == getIndex()) {
                            mListener.onPlayError((NewBannerPlayerView) getSelf());
                        }
//                        loadImage();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(mImageView);
    }

    @Override
    public void play() {
        Log.e("fafadfa", "play()");
//        if (mPlaying) {
//            return;
//        }
        log(Log.INFO, "index=" + getIndex() + ",执行play");

        mPlaying = true;
//        Log.d("tag_mPlayNextTask", "play");
        removeCallbacks();

        if (mData.getType() == BannerData.TYPE_VIDEO) {
            // 播放
            mPlayerView.startPlayLogic();
        } else if (mData.getType() == BannerData.TYPE_IMAGE) {
            if (mImageTarget != null) {
                if (isFailed) {
                    loadImage();
                }
            }
        }
        if (mPlayAttrs != null) {
            if (mData.getType() == BannerData.TYPE_IMAGE || mPlayAttrs.forcePlayDuration) {
//                Log.d("tag_mPlayNextTask", "等待播放结束" + "_" + mPlayAttrs.playDuration);
                // 强制播放时间的话，延时执行停止
                mHandler.postDelayed(mRunStopPlay, mPlayAttrs.playDuration);
            }
        }
    }


    private Runnable mRunPlay = new Runnable() {
        @Override
        public void run() {
            play();
        }
    };

    private Runnable mRunStopPlay = new Runnable() {
        @Override
        public void run() {
//            Log.d("tag_mPlayNextTask", "播放结束" + mPlaying);
            if (mPlaying) {
//                Log.d("tag_mPlayNextTask", "播放结束");
                onStop();
            }
        }
    };

    @Override
    public void pause() {

        mPlaying = false;

        log(Log.DEBUG, "index=" + getIndex() + ",执行pause");
//        Log.d("tag_mPlayNextTask", "pause");
        removeCallbacks();
        if (mData.getType() == BannerData.TYPE_VIDEO) {
            // 暂停
            mPlayerView.onVideoPause();
        }
    }

    @Override
    public void resume() {

        //mPlaying = false;
//        if (mPlaying) {
//            return;
//        }
        log(Log.DEBUG, "index=" + getIndex() + ",执行resume");
//        Log.d("tag_mPlayNextTask", "resume");
        removeCallbacks();
        // 开启
        mPlaying = true;
        if (mData.getType() == BannerData.TYPE_VIDEO) {

            mPlayerView.onVideoResume();

        } else {
            if (mImageTarget != null) {
                if (isFailed) {
                    loadImage();
                }
            }
        }
        if (mPlayAttrs != null) {
            if (mData.getType() == BannerData.TYPE_IMAGE || mPlayAttrs.forcePlayDuration) {
                // 强制播放时间的话，延时执行停止
//                Log.d("tag_mPlayNextTask", "倒计时结束" + "_resume");
                mHandler.postDelayed(mRunStopPlay, mPlayAttrs.playDuration);
            }
        }
    }

    private void removeCallbacks() {
        if (mHandler != null) {
//            Log.d("tag_mPlayNextTask", "清掉" + "_");
            mHandler.removeCallbacks(mRunPlay);
            mHandler.removeCallbacks(mRunStopPlay);
        }

    }

    public void onStop() {
        mPlaying = false;
//        Log.d("tag_mPlayNextTask", "onStop");
        log(Log.WARN, "index=" + getIndex() + ",执行onStop");
        if (mData.getType() == BannerData.TYPE_VIDEO) {
            stopVideo();

        }
        if (mListener != null && mPlayAttrs != null && mPlayAttrs.currentIndex == getIndex()) {
            mListener.onPlayComplete((NewBannerPlayerView) getSelf());
        }
    }

    //
    @Override
    public void stop() {
        mPlaying = false;
        //log(Log.WARN, "index=" + getIndex() + ",执行stop");
//        Log.d("tag_mPlayNextTask", "stop");
        removeCallbacks();
        stopVideo();
    }

    private void stopVideo() {
        if (mData.getType() == BannerData.TYPE_VIDEO) {
            // 播放
            mPlayerView.releaseVideos();
        }
    }

    @Override
    public void release() {

        mPlaying = false;

        try {
//            Log.d("tag_mPlayNextTask", "release");
            removeCallbacks();
            stopVideo();
//            mPlayerView.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public View getSelf() {
        return this;
    }

    @Override
    public void setConfig(PlayAttrs playAttrs, WeakHandler handler) {
        mPlayAttrs = playAttrs;
        mHandler = handler;
    }

    @Override
    public void setPlayTag(String tag) {
        this.tag = tag;
    }

    @Override
    public boolean isPlaying() {
        if (mData.getType() == BannerData.TYPE_VIDEO) {
            mPlaying = mPlayerView.getCurrentPlayer().isInPlayingState();
        }
        return mPlaying;
    }


    @Override
    public int compareTo(@NonNull NewBannerPlayerView o) {
        return this.getIndex() - o.getIndex();
    }

    private void log(int logLevel, String msg) {

        if (SHOW_LOG) {

            switch (logLevel) {
                case Log.VERBOSE:
                    Log.v(TAG, msg);
                    break;
                case Log.DEBUG:
                    Log.d(TAG, msg);
                    break;
                case Log.INFO:
                    Log.i(TAG, msg);
                    break;
                case Log.WARN:
                    Log.w(TAG, msg);
                    break;
                case Log.ERROR:
                    Log.e(TAG, msg);
                    break;
            }
        }
    }
}
